/*
 * @Author: Dorange.Wang
 * @Date: 2021-05-28 17:27:37
 * @LastEditors: wangming
 * @LastEditTime: 2022-06-21 17:18:03
 * @Description: file content
 */
import { setConfig, getValue, setValue } from './vmEvents';
import { cloneDeep } from "lodash";
const runEventNameDebounce = (async function (name, { values, list, key }) {
  await this.$nextTick();
  const evList = list.find((i) => i.value === name)?.children;
  if (evList?.length > 0) {
    await this.vmEvents.runEvents(evList, { _this: this, values, key });
  }
})
export default {
  vmCommonEvents: {
    setConfig,
    getValue,
    setValue,
  },
  inject: {
    parentLayout: {
      default: null,
    },
    Events: {
      default: null,
    },
    formState: {
      default: null,
    }
  },
  computed: {
    vmFormState() {
      if (!!this.formState && !this.isEdit) {
        return this.formState();
      }
    },
    vmEvents() {
      if (!!this.Events && !this.isEdit) {
        return this.Events();
      }
    },
  },
  watch: {
    vmEvents: {
      handler(V) {
        !this.isEdit && !!V?.setVm && V.setVm(this);
      },
      immediate: true,
    },
  },
  methods: {
    getformData(values = {}, formKeys = []) {
      //隐藏域逻辑
      let formData = cloneDeep(values);
      if (formKeys?.length > 0) {
        //识别特殊查询的key
        let searchKeys = [];
        for (let i in formData) {
          let key = i?.split(":")[1],
            vk = formData[i];
          if (!!key && !this.hasUnValue(vk)) {
            searchKeys.push(key);
          }
        }
        formKeys.forEach((i) => {
          let v = formData[i.key];
          this.hasUnValue(v) &&
            searchKeys.indexOf(i.key) === -1 &&
            (formData[i.key] = i.value);
        });
      }
      return formData;
    },
    hasUnValue(value) {
      return value === undefined || value === "" || value === null;
    },
    runEventName(
      name,
      { values, list = this.config.__highSetUp.events, key } = {}
    ) {
      return new Promise((resolve, reject) => {
        runEventNameDebounce.call(this, name, { values, list, key }).then((res) => {
          resolve(res)
        }).catch(err => {
          reject(err)
          !!err && console.log(err)
        })
      })
    }
  }
};
